package com.base.cn.platform.os.controller.mobile.user.center.learningCenter;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecordExpand;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.cou.record.CourseLearnFlowService;
import com.base.cn.platform.os.service.course.cou.record.CoursePlayRecordService;
import com.base.cn.platform.os.service.course.material.CouMaterialService;
import com.base.cn.platform.os.service.course.open.CourseOpenService;
import com.base.cn.platform.os.service.exam.extend.ExamUserExpandService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


/**
 * 学习中心Controller
 */
@Controller
@RequestMapping("/mobile/uc")
public class MobileLearningCenterController extends MobileBaseController {
    @Autowired
    private ExamUserExpandService examUserExpandService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CourseOpenService courseOpenService;
    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private CouMaterialService couMaterialService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CourseLearnFlowService courseLearnFlowService;
    @Autowired
    private CoursePlayRecordService coursePlayRecordService;
    @Autowired
    private TTServiceUtils ttServiceUtils;


    /**
     * 学员学习中心
     */
    @RequestMapping("/learningCenter")
    public String learningCenter(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", webMobileLoginUtil.getLoginUserId(request));
        Integer count = courseCatalogService.queryCurrentCount(params);
        request.setAttribute("count", count);
        return resultPage("/user/center/learningCenter/learning-center");
    }

    /**
     * 学习榜
     *
     * @param model
     * @return
     */
    @RequestMapping("/rankingList")
    public String rankingList(Model model) {
        return resultPage("/user/center/learningCenter/ranking-list");
    }

    /**
     * 学习榜加载
     *
     * @param model
     * @param condition
     * @param currentPage
     * @return
     */
    @RequestMapping("/ajax/rankingList")
    public String ajaxRankingList(Model model, @RequestBody UserCondition condition, @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage) {
        condition.setOrderBy(3);
        if (currentPage > 10) {
            PageInfo<CusUser> pageInfo = new PageInfo<CusUser>();
            pageInfo.setPages(1);
            model.addAttribute("dataMap", pageInfo);
            return resultPage("/user/center/learningCenter/ajax-ranking-list");
        }
        PageInfo<CusUser> pageInfo = cusUserService.findUserListPage(condition, currentPage, 10);
        model.addAttribute("dataMap", pageInfo);

        return resultPage("/user/center/learningCenter/ajax-ranking-list");
    }


    /**
     * 课程列表
     *
     * @return
     */
    @RequestMapping("/courseList")
    public String courseList(Model model) {
        return resultPage("/user/center/learningCenter/course-list");
    }

    /**
     * 加载课程列表数据
     *
     * @param model
     * @param params      查询条件
     * @param currentPage 页码
     * @return 列表页面
     */
    @RequestMapping("/ajaxCourseList")
    public String ajaxCourseList(HttpServletRequest request, Model model,
                                 @RequestBody CourseBuyRecordExpand params,
                                 @RequestParam(value = "currentPage", required = false, defaultValue = "0") int currentPage) {

        params.setUserId(webMobileLoginUtil.getLoginUserId(request));
        params.setCourseStatus(OrderStatus.SUCCESS);
        params.setSetCourseData(true);
        params.setSetStudySpeed(true);
        params.setVerifyPracticeHave(true);
        Map<String, Object> dataMap = courseBuyRecordService.findCourseBuyRecordLearnPage(params, currentPage, 10);
        model.addAttribute("dataMap", dataMap);

        return resultPage("/user/center/learningCenter/ajax-course-list");
    }

    /**
     * 页面上的统计数据
     *
     * @param request
     * @return
     */
    @RequestMapping("/userStudyBaseStatistics")
    @ResponseBody
    public Map<String, Object> userStudyBaseStatistics(HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> examUserExpand = examUserExpandService.findExamUserExpandByUserId(userId);
        dataMap.put("examUserExpand", examUserExpand);
        UserCondition condition = new UserCondition();
        condition.setId(userId);
        condition.setNotStudy(true);
        Map<String, Object> user = cusUserService.userStudyInfo(condition);
        user.remove("password");
        user.remove("customerkey");
        dataMap.put("user", user);
        return ResultUtil.SUCCESS(dataMap);
    }

//    /**
//     * 直播课程表
//     */
//    @RequestMapping("/classSchedule")
//    public String classSchedule(Model model) {
//        return resultPage("/user/center/learningCenter/class-schedule");
//    }

    /**
     * 直播课表数据
     *
     * @return
     */
    @RequestMapping("/classSchedule")
    public String toHistoryOpen() {
        return resultPage("/user/center/schedule/class-schedule");
    }


    /**
     * 加载直播课表数据
     *
     * @param model
     * @param request
     * @param params
     * @return
     */
    @RequestMapping("/ajax/load/classSchedule")
    public String ajaxHistoryOpen(Model model,
                                  HttpServletRequest request,
                                  @RequestBody Map<String, Object> params) {
        int year = (int) params.get("year");
        int month = (int) params.get("month");
        int date = (int) params.get("date");
        Date now = DateUtils.parseDate(year + "-" + month + "-" + date, "yyyy-MM-dd");
        params.put("nowDate", now);
        params.put("status", 1);
        params.put("nodeType", 2);
        params.put("userId", webMobileLoginUtil.getLoginUserId(request));
        params.put("courseStatus", OrderStatus.SUCCESS);
        model.addAttribute("userId", webMobileLoginUtil.getLoginUserId(request));
        if (ObjectUtils.isNotEmpty(params.get("courseTypeKey")) && "OPEN".equals(params.get("courseTypeKey"))) {
            List<Map<String, Object>> courseOpenList = courseOpenService.findCourseOpenList(params, false, true, false, true);
            model.addAttribute("courseOpenList", courseOpenList);
            return resultPage("/user/center/schedule/ajax-open-history");
        } else {
            List<CourseCatalog> dataMap = courseCatalogService.findCourseCatalogPage(params);
            model.addAttribute("dataMap", dataMap);
            return resultPage("/user/center/schedule/ajax-class-schedule");
        }

    }


    @RequestMapping("/ajax/findMaterialId")
    @ResponseBody
    public Map<String, Object> findMaterialId(HttpServletRequest request,
                                              @RequestParam("materialId") BigDecimal materialId,
                                              @RequestParam("courseId") BigDecimal courseId,
                                              @RequestParam("catalogId") BigDecimal catalogId,
                                              @RequestParam("livePlayState") String livePlayState) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object>  userInfo = cusUserService.userInfo(userId,false,false,false,false,false,false,false);
        Map<String, Object> material = couMaterialService.findMaterialById(materialId, false, false);
        TreeMap<String, String> VLASPROVIDER = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        material.put("liveAccount", VLASPROVIDER.get("ccAppId"));
        Integer duration = coursePlayRecordService.findUserCatalogDuration(userId, courseId, catalogId);
        material.put("duration",duration);
        if("TT".equals(material.get("playType").toString())){ //3t播放数据
            if("1".equals(livePlayState) || "4".equals(livePlayState)){//正在直播
                Map params = new HashMap();
                params.put("classId", material.get("roomId"));
                params.put("role", "3");
                params.put("uuid", userInfo.get("id").toString());
                params.put("nickName", userInfo.get("nickname"));
                params.put("avatar", userInfo.get("avatar"));
                Map<String, Object> LiveParamMap = ttServiceUtils.getLiveParam(params);
                Map resultMap = new HashMap();
                if ((boolean) LiveParamMap.get("success")) {
                    resultMap = new HashMap();
                    Map entityMap = (Map) LiveParamMap.get("entity");
                    resultMap.put("roomId", entityMap.get("classId"));
                    resultMap.put("userId", entityMap.get("UID"));
                    resultMap.put("safeKey", entityMap.get("safeKey"));
                    resultMap.put("timeStamp", entityMap.get("timeStamp"));
                    resultMap.put("expires", entityMap.get("expires_in"));
                    material.put("tLiveParams",resultMap);
                }
            }
        }
        return material;
    }

    /**
     * 学习排行榜
     */
    @RequestMapping("/learnRankingList")
    public String learnRankingList(Model model) {
        return resultPage("/user/center/learningCenter/ranking-list");
    }

    /**
     * 学习历史记录示图
     */
    @RequestMapping("/learnLineHistory")
    public String learnLineHistory(HttpServletRequest request, Model model) {
        //获取计算可用时间
        JsonObject loginUser = webMobileLoginUtil.getLoginUser(request);
        long createTime = DateUtils.parseDate(loginUser.get("createTime").getAsString(), "yyyy-MM-dd HH:mm:ss").getTime();

        model.addAttribute("dateData", createTime);
        return resultPage("/user/center/learningCenter/learning-history");
    }


    /**
     * 学员学习中心
     */
    @RequestMapping("/learningTrend")
    @ResponseBody
    public List<Map<String, Object>> learningTrend(HttpServletRequest request, @RequestBody Map params) {
        params.put("userId", webMobileLoginUtil.getLoginUserId(request));
        return courseLearnFlowService.selectLearningTrend(params);
    }

    /**
     * 学员学习中心
     */
    @RequestMapping("/learningNumerical")
    @ResponseBody
    public Map<String, Object> learningNumerical(HttpServletRequest request, @RequestBody Map params) {
        params.put("userId", webMobileLoginUtil.getLoginUserId(request));
        return cusUserService.learningNumerical(params);
    }

    /**
     * 获取用户的直播时间
     * @param request
     * @return
     */
    @RequestMapping("/ajax/findLiveTime")
    @ResponseBody
    public Map<String, Object> findLiveTime(HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<String> stringList = courseCatalogService.findLiveTime(userId);
        return ResultUtil.SUCCESS(stringList);

    }
}